package worker

import (
	"context"
	"lancer/enum"
	"log"
	"os/exec"
	"runtime"
)

func InitExecutor() (err error) {
	GExecutor = &Executor{}
	return
}

type Executor struct {
}

var (
	GExecutor *Executor
)

func (executor *Executor) ExecuteJob(command string) string {
	var (
		sysType   string
		actor     string
		cmd       *exec.Cmd
		cancelCtx context.Context
		output    []byte
		err       error
	)

	//获取操作系统类型，除了window系统其他都是按照类unix处理或者后续添加
	sysType = runtime.GOOS

	//执行shell命令
	if sysType == "windows" {
		actor = enum.WindowsExecutor
	} else {
		actor = enum.UnixExecutor
	}

	cancelCtx, _ = context.WithCancel(context.TODO())
	log.Println("执行命令:" + command)
	cmd = exec.CommandContext(cancelCtx, actor, "-c", command)

	if output, err = cmd.CombinedOutput(); err != nil {
		log.Println("执行命令报错，请把命令单独拿出来执行查看报错！！！")
		log.Println(string(output))
		panic(err)

	}

	return string(output)

}
